#include "../Logs/wmglog.h"

#include <thread>
#include <chrono>
#include <algorithm>
void beach(const std::string& logger_name,size_t thr_count,size_t msg_count,size_t msg_len)
{
    //1.获取日志器
    wmhLog::Logger::ptr logger=wmhLog::getLogger(logger_name);
    if(logger.get()==nullptr)   return;

    std::cout<<"测试日志："<<msg_count<<"条，总大小："<<(msg_count*msg_len)/1024<<"KB\n";

    //2.组织指定长度的日志消息
    std::string msg(msg_len-1,'A');//留一个换行符
    //3.创建指定数量的线程
    std::vector<std::thread> threads;
    std::vector<double> cost_arry(thr_count);;
    //总日志数量/线程数量=每个线程要输出的日志数量
    size_t msg_ptr_thr=msg_count/thr_count;

    for(int i=0;i<thr_count;i++)
    {
        threads.emplace_back([&,i](){
            //4.线程函数内部开始计时
            auto start=std::chrono::high_resolution_clock::now();
            //5.开始循环写日志
            for(int j=0;j<msg_ptr_thr;j++)
            {
                logger->fatal("%s",msg.c_str());
            }
            //线程内部结束计时
            auto end=std::chrono::high_resolution_clock::now();
            std::chrono::duration<double> cost=end-start;
            cost_arry[i]=cost.count();
            std::cout<<"线程"<<i<<"："<<"\t输出数量"<<msg_ptr_thr<<",耗时"<<\
            cost.count()<<"s"<<std::endl;
        }
        );
    }

    for(int i=0;i<thr_count;i++)
    {
        threads[i].join();
    }

    //7.计算总耗时：多线程中，并发执行；耗时最久的就是总时间
    double max_cost=cost_arry[0];
    for(int i=1;i<thr_count;++i)
    {
        max_cost=std::max(max_cost,cost_arry[i]);
    }
    //每秒输出日志数量=消息数量/消息总耗时
    size_t msg_per_sec=msg_count/max_cost;
    //每秒输出日志大小=（消息数量*消息长度=消息总大小）/总耗时
    size_t size_per_sec=(msg_count*msg_len)/(max_cost*1024);
    //8.输出打印
    std::cout<<"每秒输出日志数量:"<<msg_per_sec<<"条\n";
    std::cout<<"每秒输出日志大小:"<<size_per_sec<<"KB\n";
}



void sync_beanch()
{
    std::unique_ptr<wmhLog::LoggerBuilder> builder(new wmhLog::GlobalLoggerBuilder());
    builder->buildLoggerName("sync_logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(wmhLog::LoggerType::LOGGER_SYNC);
    // builder->buildEnableUnSafeAsync();非安全模式不提倡
    builder->buildSink<wmhLog::FileSink>("./logfile/sync.log");
    builder->build();

    beach("sync_logger",3,1000000,100);
}
void Async_bench()
{

    std::unique_ptr<wmhLog::LoggerBuilder> builder(new wmhLog::GlobalLoggerBuilder());
    builder->buildLoggerName("Async_logger");
    builder->buildFormatter("%m%n");
    builder->buildLoggerType(wmhLog::LoggerType::LOGGER_SYNC);
    builder->buildEnableUnSafeAsync();//开启非安全模式，只需要往内存里面写，不需要等待将数据写入磁盘
    builder->buildSink<wmhLog::FileSink>("./logfile/Async.log");
    builder->build();

    beach("Async_logger",3,1000000,100);
}



int main()
{
    Async_bench();
    return 0;

}